package com.example.pingapplication2.viewModel;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

/**
 * 保存系统状态的viewModel
 */
public class StateViewModel extends ViewModel {
    public MutableLiveData<Integer> flag = new MutableLiveData<>(0);//当前系统的状态，0：未工作，1：倒计时模式，2：连续丢包模式，>3：报错！
    public MutableLiveData<Integer> time = new MutableLiveData<>(0);//系统运行的时间，单位：s
    public MutableLiveData<Integer> packetNum = new MutableLiveData<>(0);//ping包的数量，用来计算ping的总时间
    public MutableLiveData<Double> packetLoss = new MutableLiveData<>(100.0);//丢包率，以百分比的形式记录
    public MutableLiveData<Integer> successNum = new MutableLiveData<>(0);//ping包成功的数量
    public MutableLiveData<Integer> failureNum = new MutableLiveData<>(0);//ping包失败的数量

    public synchronized void packetNumAdd(){
        int num = packetNum.getValue();
        num++;
        packetNum.postValue(num);
    }

    public synchronized void successNumAdd(){
        int num = successNum.getValue();
        num++;
        successNum.postValue(num);
    }

    public synchronized void failureNumAdd(){
        int num = failureNum.getValue();
        num++;
        failureNum.postValue(num);
    }


    public synchronized void calPacketLoss(){
        double failure = (double) failureNum.getValue();
        double total = (double) packetNum.getValue();
        double loss = failure * 100 / total;
        packetLoss.postValue(loss);
    }
}
